package com.dubbo.service.impl;

import com.dubbo.common.ResponseUtil;
import com.dubbo.common.push.JpushClientUtil;
import com.dubbo.domain.*;
import com.dubbo.domain.Process;
import com.dubbo.domain.info.ResultMessage;
import com.dubbo.mapper.*;
import com.dubbo.service.business.pay.WalletPayService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 钱包支付
 * @author lihongwu
 * 2019年1月9日 上午10:30:06
 */
@Service
@Transactional(readOnly=false,rollbackFor=Exception.class)
public class WalletPayServiceImpl implements WalletPayService {
	
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ProcessMapper processMapper;
	@Autowired
	private WalletMapper walletMapper;
	@Autowired
	private WalletAmountMapper walletAmountMapper;
	@Autowired
	private WalletAmountKeyMapper walletAmountKeyMapper;
	@Autowired
	private AmountOrdertKeyMapper amountOrdertKeyMapper;
	@Autowired
	private ORoleLevelMapper oRoleLevelMapper;
	@Autowired
	private UserMapper userMapper;
	
	/**
	 * 钱包支付订单
	 *
	 * @author lihongwu
	 * 2019年1月9日 上午10:43:13
	 * @param user
	 * @param orderId
	 * @return
	 * @throws Exception 
	 */
	@Override
	public Map<String, Object> walletPayOrder(User user, String orderId) throws Exception {
		Map<String,Object> check = checkWalletPayOrderParam(user,orderId);
		if(check!=null) {
			return check;
		}
		//订单
		Order order = orderMapper.selectByPrimaryKey(orderId);
		//订单流程
		Process process = new Process();
		process.setOrderid(orderId);
		process = processMapper.selectOne(process);
		//获取用户钱包
		Wallet wallet = walletMapper.getWalletByUserId(user.getId());
		//减去钱包金额
		walletMapper.walletPaySubMoney(order.getAgentprice(), wallet.getId());
		
		wallet = walletMapper.selectByPrimaryKey(wallet.getId());
		BigDecimal bd = new BigDecimal(wallet.getMoney());
		if(bd.compareTo(new BigDecimal("0"))==-1){
			 throw new Exception("您操作的次数繁忙,请稍后重试");
		}
		
		//添加钱包收支记录
		WalletAmount walletAmount = new WalletAmount();
		walletAmount.setId(UUID.randomUUID().toString().replace("-", ""));
		walletAmount.setOrderNum(order.getId());
		walletAmount.setAmount("-"+order.getAgentprice());
		walletAmount.setNote("加盟金支付订单");
		walletAmount.setPaytype(0);  //钱包支付
		//walletAmount.setStatus(11);
		walletAmount.setCreateTime(new Date());
		walletAmount.setUpdateTime(new Date());
		walletAmountMapper.insertSelective(walletAmount);
		//添加钱包-收支记录关联
		WalletAmountKey walletAmountKey = new WalletAmountKey();
		walletAmountKey.setWalletid(wallet.getId());
		walletAmountKey.setAmountid(walletAmount.getId());
		walletAmountKeyMapper.insertSelective(walletAmountKey);
		//添加订单-加盟金支付记录关联
		AmountOrdertKey amountOrdertKey = new AmountOrdertKey();
		amountOrdertKey.setOrderid(orderId);
		amountOrdertKey.setAmountid(walletAmount.getId());
		amountOrdertKeyMapper.insert(amountOrdertKey);
		
		//修改订单
		order.setPaytype(3); //钱包支付
		order.setPayTime(new Date());
		order.setPaystatus(1);
		order.setUpdateTime(new Date());
		orderMapper.updateByPrimaryKeySelective(order);
		//修改订单流程状态
		process.setStatus(7);  //厂家待批准状态
		process.setUpdateTime(new Date());
		processMapper.updateByPrimaryKeySelective(process);
		
//		 消息推送给代理商
		JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
		if(user!=null&& StringUtils.isNotBlank(user.getRegistrationId())) {
			JpushClientUtil.sendToRegistrationId(user.getRegistrationId(), "订单通知", "订单通知", "订单支付成功,等待发货中!", "", "", "", new HashMap<>());
		}
		ORoleLevel oRoleLevel = new ORoleLevel();
		oRoleLevel.setOrderid(orderId);
		oRoleLevel = oRoleLevelMapper.selectOne(oRoleLevel);
		if(oRoleLevel!=null){
			if(StringUtils.isNotBlank(oRoleLevel.getTraderid())){
				//消息推送给分销商
				User Trader = userMapper.selectByPrimaryKey(oRoleLevel.getTraderid());
				JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
				if(Trader!=null&&StringUtils.isNotBlank(Trader.getRegistrationId())) {
					JpushClientUtil.sendToRegistrationId(Trader.getRegistrationId(), "订单通知", "订单通知", "代理商已接单!", "", "", "", new HashMap<>());
				}
			}
			if(StringUtils.isNotBlank(oRoleLevel.getElectid())){
				//消息推送给分销商
				User Elect = userMapper.selectByPrimaryKey(oRoleLevel.getElectid());
				JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
				if(Elect!=null&&StringUtils.isNotBlank(Elect.getRegistrationId())) {
					JpushClientUtil.sendToRegistrationId(Elect.getRegistrationId(), "订单通知", "订单通知", "代理商已接单!", "", "", "", new HashMap<>());
				}
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	/**
	 * 校验钱包支付订单接口的参数
	 *
	 * @author lihongwu
	 * 2019年1月9日 上午10:45:36
	 * @param user
	 * @param orderId
	 * @return
	 */
	private Map<String, Object> checkWalletPayOrderParam(User user, String orderId) {
		if(!StringUtils.isNotBlank(orderId)) {
			return ResponseUtil.ajaxCheckError("系统繁忙,请稍后重试~", "orderId");
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if(order==null) {
			return ResponseUtil.ajaxCheckError("系统繁忙,请稍后重试~", "orderId");
		}
		if(order.getPaystatus().equals(1)) {
			return ResponseUtil.ajaxCheckError("系统繁忙,请稍后重试~", "payStatus");
		}
		
		Process process = new Process();
		process.setOrderid(orderId);
		process = processMapper.selectOne(process);
		if(process==null) {
			return ResponseUtil.ajaxCheckError("系统繁忙,请稍后重试~", "process is null");
		}
		//若订单状态不是代理商代审核阶段
		if(process.getStatus()!=5) {
			return ResponseUtil.ajaxCheckError("系统繁忙,请稍后重试~", "status is error");
		}
		
		//获取用户钱包
		Wallet wallet = walletMapper.getWalletByUserId(user.getId());
		
		if(Double.valueOf(wallet.getMoney())<Double.valueOf(order.getAgentprice())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.MONEY_NOT_ENOUGHT);
		}
		return null;
	}
	
	
}
